package org.base.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
//import org.apache.shiro.authc.AuthenticationException;
import org.base.common.pojo.Result;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handleBindException(MethodArgumentNotValidException e) {
        printError(e);
        Optional<String> msgOptional = e.getBindingResult().getFieldErrors().stream()
                .map(f -> f.getField() + ":" + f.getDefaultMessage()).reduce((a, b) -> a + " " + b);
        log.warn("检验参数异常：{}", msgOptional.get());
        return new Result(ExceptionEnum.ERROR_ARGUMENT.getStatus(), msgOptional.get());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public Result badArgumentHandler(IllegalArgumentException e) {
        printError(e);
        return new Result(ExceptionEnum.ERROR_ARGUMENT.getStatus(), ExceptionEnum.ERROR_ARGUMENT.getMsg());
    }


    private void printError(Exception e) {
        log.error(e.getMessage(), e);
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Result badArgumentHandler(MethodArgumentTypeMismatchException e) {
        printError(e);
        return new Result(ExceptionEnum.ERROR_ARGUMENT.getStatus(), ExceptionEnum.ERROR_ARGUMENT.getMsg());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public Result badArgumentHandler(MissingServletRequestParameterException e) {
        printError(e);
        return new Result(ExceptionEnum.ERROR_ARGUMENT.getStatus(), ExceptionEnum.ERROR_ARGUMENT.getMsg());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result badArgumentHandler(HttpMessageNotReadableException e) {
        printError(e);
        return new Result(ExceptionEnum.ERROR_ARGUMENT.getStatus(), ExceptionEnum.ERROR_ARGUMENT.getMsg());
    }

    @ExceptionHandler(ValidationException.class)
    @ResponseBody
    public Result badArgumentHandler(ValidationException e) {
        printError(e);
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
                return new Result(ExceptionEnum.ERROR_ARGUMENT_WITH_DESC.getStatus(), message);
            }
        }
        return new Result(ExceptionEnum.ERROR_ARGUMENT.getStatus(), ExceptionEnum.ERROR_ARGUMENT.getMsg());
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result businessException(Exception e) {
        printError(e);
        BusinessException be = (BusinessException) e;
        return new Result(be.getStatus(), be.getMessage());
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result bindException(Exception e) {
        printError(e);
        BindException bindException = (BindException) e;
        List<String> errors = new ArrayList<>();
        for (ObjectError allError : bindException.getBindingResult().getAllErrors()) {
            errors.add(allError.getDefaultMessage());
        }
        return new Result(ExceptionEnum.ERROR_ARGUMENT_BIND.getStatus(), StringUtils.join(errors, ", "));
    }

//    @ExceptionHandler(AuthenticationException.class)
//    @ResponseBody
//    public Result authenticationException(Exception e) {
//        return Result.error(ExceptionEnum.USERNAME_OR_PASSWORD_ERROR);
//    }



    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result seriousHandler(Exception e) {
        printError(e);
        return new Result(ExceptionEnum.UNKNOWN.getStatus(), e.getMessage());
    }

}
